//------------------------------------------------------------
// * Author         : Ekko
// * Description    : HTTP工具类
//------------------------------------------------------------

export class HttpUtils{

    // private static baseUrl : string = "https://xxx.xxx.xxx/xxxx/";

    /**
     * HTTP GET请求
     * @param url 地址
     * @param params 参数
     * @param callback 回调
     */
    public static Get(url, params : object = {}, callback){
        let dataStr = '';
        Object.keys(params).forEach(key => {
            dataStr += key + '=' + params[key] + '&';
        })

        if (dataStr != ''){
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }

        // url = this.baseUrl + url;
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
               if (xhr.status >= 200 && xhr.status < 300){
                    let response = xhr.responseText;
                    callback(true, JSON.parse(response));
                }else{
                    callback(false, this.response);
               }
            }
        };

        xhr.send();
    }

    /**
     * HTTP POST请求
     * @param url 地址
     * @param param 参数
     * @param callback 回调
     */
    public static Post(url, param : object = {}, callback){
        // url = this.baseUrl + url;
        var xhr = cc.loader.getXMLHttpRequest();
        let dataStr = '';
        Object.keys(param).forEach(key => {
            dataStr += key + '=' + param[key] + '&';
        })  

        if(dataStr != ''){
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
        }
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                let response = xhr.responseText;
                if(xhr.status >= 200 && xhr.status < 300){
                    let httpStatus = xhr.statusText;
                    callback(true, JSON.parse(response));
                }else{
                    callback(false, response);
                }
            }
        };
        xhr.send(dataStr);
    }
}